package cn.good.yan.handle;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 重写，登录成功后，跳转的请求 - 调整到外部地址
 * 输入地址，http://localhost:8081/login.html
 * 进行登录，用户admin 密码123 ，输入正确，跳转百度
 * 输入错误，进入 MyAuthenticaFailtHandler 里的逻辑
 *
 * @author shengren.yan
 * @create 2024/9/26
 */
public class MyAuthenticatHandler implements AuthenticationSuccessHandler {

    private String url;

    // 构造函数
    public MyAuthenticatHandler(String url) {
        this.url = url;
    }

    @Override
    public void onAuthenticationSuccess(
            HttpServletRequest request,
            HttpServletResponse response,
            Authentication authentication) throws IOException, ServletException {

        // 打印IP地址，请求来的IP地址
        System.out.println(request.getRemoteUser());

        User user = (User) authentication.getPrincipal();

        System.out.println(user.getUsername());    // 用户名
        System.out.println(user.getPassword());    // 密码
        System.out.println(user.getAuthorities()); // 权限

        // 重写跳转到该地址（url）
        response.sendRedirect(url);

    }

}
